<template>
  <div class="edit-signature">
    <el-form>
      <el-form-item label="个性签名">
        <el-input
          ref="signatureRef"
          v-model.trim="signature"
          type="textarea"
          placeholder="编辑个签，让自己变得更有个性"
          show-word-limit
          :maxlength="40"
          :autosize="{ minRows: 3, maxRows: 3 }"
          resize="none"
          @keyup.enter.prevent="isSubmitForm(signature)" /></el-form-item
    ></el-form>
    <div class="submit-signature">
      <el-button
        class="submit-signature__button"
        type="primary"
        :loading="isLoading"
        :disabled="!signature || isLoading"
        @click="submitForm(signature)"
        ><template #loading><Loading /></template>确认</el-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from "vue";
import { useUserPinia } from "@/pinia/user";
import type { ElInput } from "element-plus";
import { ElMessage } from "element-plus";

const userStore = useUserPinia();

/**
 * 给输入框一个ref属性
 */
const signatureRef = ref<typeof ElInput>();
/**
 * 用户的昵称
 */
const signature = ref<string>("");
/**
 * 是否正在发送请求
 */
const isLoading = ref<boolean>(false);

/**
 * 更新signature值
 */
const updateSignature = () => {
  if (signature.value !== userStore.user.signature)
    signature.value = userStore.user.signature;
};

// 开始发送请求
const submitForm = (signature: string) => {
  if (signature === userStore.user.signature) {
    ElMessage({
      duration: 1500,
      message: "不能和原个性签名相同",
      type: "error",
    });
    return;
  }
  isLoading.value = true;
  userStore
    .changeSignature({ signature: signature })
    .then((code: number) => {
      isLoading.value = false;
      if (code === 1)
        ElMessage({
          duration: 1500,
          message: "设置成功",
          type: "success",
        });
      else
        ElMessage({
          duration: 1500,
          message: "设置失败",
          type: "error",
        });
      nextTick(() => signatureRef.value?.focus());
    })
    .catch(() => {
      isLoading.value = false;
      nextTick(() => signatureRef.value?.focus());
      ElMessage({
        duration: 1500,
        message: "设置失败",
        type: "error",
      });
    });
};

// 用户按下Enter键是否开始发送请求
const isSubmitForm = (signature: string) => {
  if (signature) submitForm(signature);
  else
    ElMessage({
      type: "error",
      message: "个性签名不能为空",
      duration: 1500,
    });
};

onMounted(() => (signature.value = userStore.user.signature));

defineExpose({
  updateSignature,
});
</script>

<style lang="scss" scoped>
.edit-signature {
  width: 80%;
  margin-left: 20px;
}

.submit-signature {
  margin: 30px 0;

  &__button {
    width: 90%;
    margin-left: 35px;
  }
}
</style>
